/**
 * Created by PC on 2017/5/23.
 */
layui.use(['form', 'upload', 'jquery', 'layer', 'laytpl'], function () {
    var form = layui.form(),
        $ = layui.jquery,
        laytpl = layui.laytpl,
        layer = layui.layer;
    //联动对象
    var linkage = {};
    //渲染下拉框
    linkage.formRender = function (obj, tip) {
        $(obj).empty();
        $(obj).append('<option value="">' + tip + '</option>');
        form.render('select');
    };
    //读取数据库信息并写回到select框中（有数据已存在，可进行更改）
    linkage.readInit = function (obj, url, init,id) {
        axios.get(url)
            .then(function (res) {
                var array = res.data.data;
                var html = '';
                for (var i in array) {
                    html += '<option value=' + array[i].id + '>' + array[i].name + '</option>';
                }
                $(obj).append(html);
                form.render('select');
                // console.log(init);
                if (init)
                    $(obj).next().find('[lay-value="' + id + '"]').click();
            })
            .catch(function (res) {
                console.log(res);
            });
    };
    // 初始无数据存在，不可进行更改，只赋值
    linkage.read = function (obj, url) {
        axios.get(url)
            .then(function (res) {
                var array = res.data.data;
                var html = '';
                for (var i in array) {
                    html += '<option value=' + array[i].id + '>' + array[i].name + '</option>';
                }
                $(obj).append(html);
                form.render('select');
                // console.log(init);
                // if (init)
                //     $(obj).next().find('[lay-value="' + id + '"]').click();
            })
            .catch(function (res) {
                console.log(res);
            });
    };

    var
        // university = 'form select[name=university]',
        // school = 'form select[name=school]',
        department = 'form select[name=department]',
        major = 'form select[name=major]',
        clazz = 'form select[name=clazz]';

    var vm = new Vue({
        el: '#content'
        , data: {
            show: true
            ,showClass: true
            , user: {
                id: userid
            }
            , studentInfo: {
                userid:userid
            }
            , attribution: {}
            , teacherInfoInternName: ""
            , teacherInfoPaperName: ""
        }
        , methods: {
            /**
             * 修改按钮
             */
            update: function () {
                vm.show = false;
                vm.showClass = false;
                form.render('radio');
                form.render('select');
                $('#content input[type!=button]').attr("readOnly", false).removeClass("disabled");
                $('#content textarea').attr("readOnly", false).removeClass("disabled");
            },
            /**
             * 返回按钮
             */
            reload: function () {
                vm.show = true;
                vm.showClass = true;
                $('#content input[type!=button]').attr("readOnly", true).addClass("disabled");
                $('#content textarea').attr("readOnly", true).addClass("disabled");
                vm.getInfo(userid);
            },
            /**
             * 获取信息
             * @param userId
             */
            getInfo: function (userid) {
                $.ajax({
                    type: "GET",
                    url: "/student/findDetail/" + userid,
                    dataType: "json",
                    success: function (Response) {
                        // console.log(Response);
                        vm.user = Response.data.user;
                        if (Response.data.studentInfo !== null) {
                            vm.studentInfo = Response.data.studentInfo;
                        }

                        // console.log(vm.studentInfo);
                        if (vm.studentInfo !== null && Response.data.clazz !== null) {
                            vm.attribution.universityName = Response.data.university.name;
                            vm.attribution.universityid = Response.data.university.id;  //选取教师用
                            vm.attribution.schoolName = Response.data.school.name;
                            vm.attribution.departmentName = Response.data.department.name;
                            vm.attribution.majorName = Response.data.major.name;
                            vm.attribution.clazzName = Response.data.clazz.name;
                        }
                        vm.teacherInfoInternName = Response.data.teacherInfoInternName;
                        vm.teacherInfoPaperName = Response.data.teacherInfoPaperName;
                        // console.log(vm.attribution);
                        // 读取大学
                        if ($(university).length) {
                            linkage.formRender(university, "选择大学");
                            if(Response.data.clazz!=null) {
                                linkage.readInit(university, '/university/findAll', Response.data.clazz, Response.data.clazz.universityid);
                            }
                            else{
                                linkage.read(university, '/university/findAll');
                            }
                            //读取学院
                            if ($(school).length) {
                                linkage.formRender(school, "选择学院");
                                form.on('select(university)', function (data) {
                                    linkage.formRender(school, "选择学院");
                                    linkage.formRender(department, "选择系");
                                    linkage.formRender(major, "选择专业");
                                    linkage.formRender(clazz, "选择班级");
                                    if(Response.data.clazz!=null) {
                                        linkage.readInit(school, '/school/findBath/' + data.value, Response.data.clazz, Response.data.clazz.schoolid);
                                    }
                                    else{
                                        linkage.read(school, '/school/findBath/' + data.value);
                                    }
                                });
                                if ($(department).length) {
                                    linkage.formRender(department, "选择学院");
                                    form.on('select(school)', function (data) {
                                        linkage.formRender(department, "选择系");
                                        linkage.formRender(major, "选择专业");
                                        linkage.formRender(clazz, "选择班级");
                                        if(Response.data.clazz!=null) {
                                            linkage.readInit(department, '/department/findBath/' + data.value, Response.data.clazz, Response.data.clazz.departmentid);
                                        }
                                        else{
                                            linkage.read(department, '/department/findBath/' + data.value);
                                        }
                                    });
                                    if ($(major).length) {
                                        linkage.formRender(school, "选择学院");
                                        linkage.formRender(department, "选择系");
                                        form.on('select(department)', function (data) {
                                            linkage.formRender(major, "选择专业");
                                            linkage.formRender(clazz, "选择班级");
                                            if(Response.data.clazz!=null) {
                                                linkage.readInit(major, '/major/findBath/' + data.value, Response.data.clazz, Response.data.clazz.majorid);
                                            }
                                            else{
                                                linkage.read(major, '/major/findBath/' + data.value);
                                            }
                                        });
                                        if ($(clazz).length) {
                                            linkage.formRender(school, "选择学院");
                                            linkage.formRender(department, "选择系");
                                            linkage.formRender(major, "选择专业");
                                            form.on('select(major)', function (data) {
                                                // console.log(data);
                                                linkage.formRender(clazz, "选择班级");
                                                if(Response.data.clazz!=null) {
                                                    linkage.readInit(clazz, '/class/findBatchByMajorid/' + data.value, Response.data.clazz, Response.data.clazz.id);
                                                }
                                                else{
                                                    linkage.read(clazz, '/class/findBatchByMajorid/' + data.value);
                                                }
                                            });
                                        }
                                    }
                                }

                            }
                        }
                    },
                    error: function (msg) {
                        console.log(vm.user.id);
                        console.log("失败");
                        console.log(msg);
                    }
                });
            }
        }
    });

    // 首次读取信息
    vm.getInfo(userid);
    $('#content input[type!=button]').addClass("disabled");
    $('#content textarea').addClass("disabled");

    //监听提交
    form.on('submit(save)', function () {
        var url = "/student/modifyOrAddDetail";
        var data = {
            user: vm.user
            , studentInfo: vm.studentInfo
            // ,attribution:vm.attribution
        };
        console.log(data);
        axios.post(url, data)
            .then(function (response) {
                // console.log(response);
                if (response.data.success)
                    layer.msg("保存成功", {icon: 1, time: 1000}, function () {
                        vm.reload();
                    });
                else {
                    layer.msg(response.data.message, {icon: 2, time: 1000}, function () {
                        vm.reload();
                    });
                }
            })
            .catch(function (response) {
                console.log(response);
            });
        return false;
    });


    //教师弹框中下拉框模板
    var select = '<form class="layui-form" style="margin:20px 20px 0px">\
                        <div class="layui-form-item">\
                            <label class="layui-form-label">请选择教师</label>\
                            <div class="layui-input-block">\
                                <select name="teacherApply" id="teacherApply" lay-search>\
                                    <option value="">请选择</option>\
                                </select>\
                            </div>\
                        </div>\
                    </form>';

    //根据学校id获取该校全部老师并渲染教师选择下拉框
    function getTeachers() {
        // console.log(vm.attribution.universityid);
        $.ajax({
            type: "GET"
            , url: "/teacherInfo/findBatchByUniversityid/" + vm.attribution.universityid
            // ,data:vm.attribution.universityid
            , dataType: "json"
            , success: function (Response) {
                // console.log(Response);
                for (var i = 0; i < Response.data.length; i++) {
                    teachers[i] = Response.data[i];
                }
                console.log(teachers.length);
                var html = '';
                for (var i = 0; i < teachers.length; i++) {
                    html += '<option value=' + teachers[i].teacherInfo.id + ' >' + teachers[i].user.realname + '</option>';
                    // console.log(html);
                }

                $("#teacherApply").append(html);
                form.render('select');
            }
            , error: function (msg) {
                console.log(vm.user.id);
                console.log("获取教师信息失败");
                console.log(msg);
            }
        });

    }

    //监听申请毕设指导老师按钮
    $("#applyPaper").click(function () {
        getTeachers();
        layer.open({
            type: 1,
            title: '申请毕业设计指导老师',
            shade: [0.5, '#FFF'], //模态框
            area: ['400px', '400px'],
            zIndex: 19950924,
            content: select,
            btn: ['提交审核', '取消'],
            yes: function (index) {
                vm.studentInfo.paperadvisor = $("#teacherApply").val();
                // console.log(JSON.stringify(vm.studentInfo));
                $.ajax({
                    type: "POST"
                    , url: "/student/modify"
                    , dataType: "json"
                    , contentType: "application/json"
                    , data: JSON.stringify(vm.studentInfo)
                    , success: function (Response) {
                        // console.log("this:  " + JSON.stringify(Response));
                        layer.close(index);
                    }
                    , error: function (msg) {
                        layer.msg('保存教师信息失败', {icon: 2, time: 1000});
                        console.log(msg);
                    }
                });
                // axios.post("/student/modifyDetail/", vm.studentInfo)
                //     .then(function (response) {
                //         console.log(123456);
                //         layer.msg(response.data.message, {time: 1500}, function () {
                //             if (response.data.success) {
                //                 layer.close(index);
                //             }
                //         });
                //     })
                //     .catch(function (response) {
                //         console.log(response);
                //     })
            },
            btn2: function (index, layero) {
                layer.close(index);
            },
            end: function (index) {
                layer.close(index);
            }
        });
        form.render("select");
    });

    //监听申请实习指导老师按钮
    $("#applyIntern").click(function () {
        getTeachers();
        layer.open({
            type: 1,
            title: '申请实习指导老师',
            shade: [0.5, '#FFF'], //模态框
            area: ['400px', '400px'],
            zIndex: 19950924,
            content: select,
            btn: ['提交审核', '取消'],
            yes: function (index) {
                vm.studentInfo.internadvisor = $("#teacherApply").val();
                vm.studentInfo.advisestate = "1";
                // console.log(vm.studentInfo.internadvisor);
                $.ajax({
                    type: "POST"
                    , url: "/student/modify"
                    , dataType: "json"
                    , contentType: "application/json"
                    , data: JSON.stringify(vm.studentInfo)
                    , success: function (Response) {
                        console.log("this:  " + JSON.stringify(Response));
                        layer.close(index);
                    }
                    , error: function (msg) {
                        layer.msg('保存教师信息失败', {icon: 2, time: 1000});
                        console.log(msg);
                    }
                });
            },
            btn2: function (index, layero) {
                layer.close(index);
            },
            end: function (index) {
                layer.close(index);
            }
        });
        form.render("select");
    });

    //监听radio
    form.on('radio(sex)', function (data) {
        // console.log(data);
        vm.user.sex = data.value;
    });

    //监听大学
    form.on('select(university)', function (data) {
        vm.attribution.universityid = data.value;
    })
    //监听班级
    form.on('select(clazz)', function (data) {
        // console.log(data);
        vm.studentInfo.classid = data.value;
    })

});